/**
 *
 * 简易封装ajax
 * @param {方法类型} method
 * @param {请求地址} url
 * @returns promise
 */
function ajax(method, url) {
  return new Promise((resolve, reject) => {
    const request = new XMLHttpRequest();
    request.open(method, url);
    request.onreadystatechange = () => {
      if (request.readyState === 4) {
        if (request.status === 200) {
          resolve(request.response);
        } else {
          reject(request);
        }
      }
    };
    request.send();
  });
}
ajax('get', 'http://qq.com:8888/friends.json').then((response) => {
  console.log('嘿嘿，我拿到了qq.com:8888的朋友列表')
  console.log(response)
})

/**
 *封装之后的jsonp
 * @param {请求资源地址} url
 */
function getJsonP(url) {
  return new Promise((resolve, reject)=> {
    const randomName = 'lucyJsonpFunctionName' + Math.random()
    window[randomName] = (data) => {
      resolve(data)
    }
    const script = document.createElement('script')
    // callback是前后端程序员默认使用的名称
    script.src = `${url}?callback=${randomName}`;
    script.onload = () => {
      //防止多个script标签，导致代码冗余
      script.remove()
    }
    script.onerror = () => {
      reject()
    }
    document.body.appendChild(script)
  });
}

getJsonP('http://qq.com:8888/friends.js').then((response) => {
  console.log(response)
})